package gui.panels;

import data.User;
import gui.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.KeyAdapter;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import maiaclient.Maia;
import maiaclient.interfaces.IChatListener;

/**
 *
 * @author groep 11
 * @date 2007-2008
 */
public class Chat extends JPanel implements IChatListener {

    private JTextPane txtpEveryone,  txtpFriends,  txtpTribe;
    private JTabbedPane tpChat;
    private JTextField txtChat;
    private JList lstUsers;
    private DefaultListModel lstmUser;
    private Maia maia;
    private AbstrWorld parent;
    private Vector<User> onlineUsers;
    private Vector<User> friends;
    private Vector<User> tribemembers;

    public Chat(Maia passedMaia, AbstrWorld passedParent) {
        parent = passedParent;
        maia = passedMaia;

        // Build the gui
        initChatPanel();

        // Add chat listener to maia's list
        maia.addChatListener(this);

        // Initialy load the online users
        updateAllOnlineUsers();
    }

    private void initChatPanel() {
        this.setLayout(new BorderLayout());
        this.setBorder(new EmptyBorder(0, 0, 10, 5));

      
        txtChat = new JTextField();

        this.add(txtChat, BorderLayout.SOUTH);

        txtChat.addKeyListener(new KeyAdapter() {

            @Override
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtchatKeyPressed(evt);
            }
        });

        tpChat = new JTabbedPane(JTabbedPane.BOTTOM);

        JScrollPane scllpEveryone = new JScrollPane();
        txtpEveryone = new JTextPane();
        txtpEveryone.setEditable(false);
        scllpEveryone.setViewportView(txtpEveryone);

        JScrollPane scllpFriends = new JScrollPane();
        txtpFriends = new JTextPane();
        txtpFriends.setEditable(false);
        scllpFriends.setViewportView(txtpFriends);

        JScrollPane scllpTribe = new JScrollPane();
        txtpTribe = new JTextPane();
        txtpTribe.setEditable(false);
        scllpTribe.setViewportView(txtpTribe);

        tpChat.addTab("Everyone", scllpEveryone);
        tpChat.addTab("Friends", scllpFriends);
        tpChat.addTab("Tribe", scllpTribe);

        tpChat.addChangeListener(new ChangeListener() {
            // This method is called whenever the selected tab changes

            public void stateChanged(ChangeEvent evt) {
                updateAllOnlineUsers();
            }
        });

        this.add(tpChat, BorderLayout.CENTER);

        lstmUser = new DefaultListModel();

        lstUsers = new ZebraJList(lstmUser);

        JScrollPane scpUsers = new JScrollPane(lstUsers);
        scpUsers.setPreferredSize(new Dimension(100, 0));
        scpUsers.setBorder(new LineBorder(Color.GRAY));
        //scpUsers.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);

        this.add(scpUsers, BorderLayout.EAST);

    }

    public void updateAllOnlineUsers() {
        onlineUsers = maia.getMaiaClient().getOnlineUsers();
        friends = maia.getMaiaClient().getFriends();
        tribemembers = maia.getMaiaClient().getTribeMembers();

        // Get selected tab
        String tabTitle = tpChat.getTitleAt(tpChat.getSelectedIndex());

        try {
            if (tabTitle.equals("Everyone")) {
                showAllOnlineUsers();
            } else if (tabTitle.equals("Friends")) {
                showFriends();
            } else if (tabTitle.equals("Tribe")) {
                showTribeMembers();
            } else { // e.g. friend's name

            }
            
        } catch (IOException ex) {
            Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /*
     * Shows the list of online users.
     */
    private void showAllOnlineUsers() throws IOException {
        lstmUser.clear();

        if (onlineUsers != null) {
            for (User u : onlineUsers) {

                if (u.getUserId() != maia.getUser().getUserId()) {
                    lstmUser.addElement(u);
                }
            }
        } else {
            maia.getMaiaClient().invokeChatListUpdate();
        }

    }

    /*
     * Shows the list of online friends
     */
    private void showFriends() throws IOException {
        lstmUser.clear();
        if (friends != null) {
            for (User f : friends) {
                for (User u : onlineUsers) {
                    if (f.getUserId() == u.getUserId()) {
                        lstmUser.addElement(f);
                    }
                }
            }
        } else {
            maia.getMaiaClient().invokeChatListUpdate();
        }
    }

    /*
     * Shows the list of online tribe members
     */
    private void showTribeMembers() throws IOException {
        lstmUser.clear();
        if (tribemembers != null) {
            for (User t : tribemembers) {
                for (User u : onlineUsers) {
                    if (t.getUserId() == u.getUserId()) {
                        lstmUser.addElement(t);
                    }
                }
            }
        } else {
            maia.getMaiaClient().invokeChatListUpdate();
        }
    }

    private void txtchatKeyPressed(java.awt.event.KeyEvent evt) {
        try {
            // Get selected tab
            String title = tpChat.getTitleAt(tpChat.getSelectedIndex());

            // When pushed at "enter" a message is send that is not empty
            if (evt.getKeyCode() == 10 && txtChat.getText().length() > 0) {
                //Break too long lines, antispam
                if (txtChat.getText().length() > 120) {
                    if (title.equals("Everyone")) {
                        maia.getMaiaClient().sendAllChatmessage(txtChat.getText().substring(0, 115));
                    } else if (title.equals("Friends")) {
                        maia.getMaiaClient().sendFriendsChatmessage(txtChat.getText().substring(0, 115));
                    } else if (title.equals("Tribe")) {
                        maia.getMaiaClient().sendTribeChatmessage(txtChat.getText().substring(0, 115));
                    }
                } else {
                    if (title.equals("Everyone")) {
                        maia.getMaiaClient().sendAllChatmessage(txtChat.getText());
                    } else if (title.equals("Friends")) {
                        maia.getMaiaClient().sendFriendsChatmessage(txtChat.getText());
                    } else if (title.equals("Tribe")) {
                        maia.getMaiaClient().sendTribeChatmessage(txtChat.getText());
                    }
                }
                txtChat.setText("");
            }
        } catch (IOException ex) {
            Logger.getLogger(MaiaWorld.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Displays chat messages graphically.
     * 3 types of messages : 0 = everyone, 1 = tribe, 2 = f
     * @param globalMessage
     * @param type
     */
    public void showChatmessage(String globalMessage, int type) {
        SimpleAttributeSet chatGlobal = new SimpleAttributeSet();
        StyleConstants.setForeground(chatGlobal, Color.black);
        StyleConstants.setBold(chatGlobal, false);
        try {
            JTextPane targetChatBox = null;
            if (type == 0) {
                targetChatBox = txtpEveryone;
            } else if (type == 1) {
                targetChatBox = txtpTribe;
            } else {
                targetChatBox = txtpFriends;
            }

            Document doc = targetChatBox.getDocument();
            insertSmile(globalMessage, targetChatBox);

            //chatvenster autoscroll:
            targetChatBox.setCaretPosition(doc.getLength());

        } catch (Exception exp) {
            exp.printStackTrace();
        }
    }

    private void insertSmile(String text, JTextPane targetChatBox) {
        Document doc = targetChatBox.getDocument();
        ImageIcon icoSmily;
        int counter = 0;
        boolean b = false;
        // layout
        SimpleAttributeSet chatGlobal = new SimpleAttributeSet();
        StyleConstants.setForeground(chatGlobal, Color.black);
        StyleConstants.setBold(chatGlobal, false);

        //check
        try {
            for (int i = 0; i < text.length() - 1; i++) {
                if (text.substring(i, i + 1).equals(":")) {
                    if (text.substring(i + 1, i + 2).equals(")")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/smile.gif");
                        targetChatBox.insertIcon(icoSmily);
                        // counter makes sure you can continue line
                        counter = i + 2;
                    }
                    if (text.substring(i + 1, i + 2).equals("D")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/biggrin.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                    if (text.substring(i + 1, i + 2).equals("p")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/puh2.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                    if (text.substring(i + 1, i + 2).equals("/")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/nosmile.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                    if (text.substring(i + 1, i + 2).equals("y")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/static.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                    if (text.substring(i + 1, i + 2).equals("t")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/nopompom.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                }
                if (text.substring(i, i + 1).equals(";")) {
                    if (text.substring(i + 1, i + 2).equals(")")) {
                        b = true;
                        doc.insertString(doc.getLength(), text.substring(counter, i), chatGlobal);
                        targetChatBox.setCaretPosition(doc.getLength());
                        icoSmily = new ImageIcon("src/img/smileys/wink.gif");
                        targetChatBox.insertIcon(icoSmily);
                        counter = i + 2;
                    }
                }
            }
            if (text.length() != counter) {
                //Still a part of the text that is not displayed
                //Check if there really was a smiley , otherwise  b== false = true then we get 2x the same line
                if (b) {
                    doc.insertString(doc.getLength(), text.substring(counter, text.length()) + "\n", chatGlobal);
                }
            } else {
                //don't forget when their is a smiley at the end we must at a "enter"
                if (b) {
                    doc.insertString(doc.getLength(), "\n", chatGlobal);
                }
            }
            if (b == false) {
                //no smiley we can put hole line
                doc.insertString(doc.getLength(), text + "\n", chatGlobal);
            }
        } catch (BadLocationException ex) {
            ex.printStackTrace();
        }
    }
}
